Comparison of Java and C++

Programming language comparisons
General comparison
Basic syntax
Basic instructions
Arrays
Associative arrays
String operations
String functions
List comprehension
Object-oriented programming
Object-oriented constructors
Database access
Database RDBMS

Evaluation strategy
List of "hello world" programs

ALGOL 58's influence on ALGOL 60
ALGOL 60: Comparisons with other languages
Comparison of ALGOL 68 and C++
ALGOL 68: Comparisons with other languages
Compatibility of C and C++
Comparison of Pascal and Borland Delphi
Comparison of Object Pascal and C
Comparison of Pascal and C
Comparison of Java and C++
Comparison of C# and Java
Comparison of C# and Visual Basic .NET

This is a comparison of the Java programming language with the C++ programming language.

Contents

Design aims

The differences between the C++ and Java programming languages can be traced to their heritage, as they have different design goals.

The different goals in the development of C++ and Java resulted in different principles and design trade-offs between the languages. The differences are as follows :

C++ Java
Compatible with C source code, except for a few corner cases. No backward compatibility with any previous language. The syntax is, however, strongly influenced by C/C++.
Write once compile anywhere (WOCA) Write once run anywhere / everywhere (WORA / WORE)
Allows procedural programming, functional programming, object-oriented programming, and template metaprogramming. Strongly encourages an object oriented programming paradigm.
Allows direct calls to native system libraries. Call through the Java Native Interface and recently Java Native Access
Exposes low-level system facilities. Runs in a protected virtual machine.
Only provides object types and type names. Is reflective, allowing metaprogramming and dynamic code generation at runtime.
Has multiple binary compatibility standards (commonly Microsoft and Itanium/GNU) Has a binary compatibility standard, allowing runtime check of correctness of libraries.
Optional automated bounds checking. (e.g. the at() method in vector and string containers) Normally performs bounds checking. HotSpot can remove bounds checking.
Supports native unsigned arithmetic. No native support for unsigned arithmetic.
Standardized minimum limits for all numerical types, but the actual sizes are implementation-defined. Standardized types are available as typedefs (uint8_t, ..., uintptr_t). Standardized limits and sizes of all primitive types on all platforms.
Pointers, References, and pass by value are supported Primitive and reference data types always passed by value.[1]
Explicit memory management, C++11 replace the old standard RAII auto_ptr<T> by unique_ptr<T> and add shared_ptr<T> (smart pointer with reference counter) though third party frameworks exist to provide better garbage collection. Supports destructors. Automatic garbage collection (can be triggered manually). Doesn't have the concept of Destructor and usage of finalize() is not recommended.
Supports class, struct, and union and can allocate them on heap or stack Supports only class and allocates them on the heap. Java SE 6 optimizes with escape analysis to allocate some objects on the stack.
Allows explicitly overriding types. Rigid type safety except for widening conversions. Autoboxing/Unboxing added in Java 1.5.
The C++ Standard Library has a much more limited scope and functionality than the Java standard library but includes: Language support, Diagnostics, General Utilities, Strings, Locales, Containers, Algorithms, Iterators, Numerics, Input/Output and Standard C Library. The Boost library offers much more functionality including threads and network I/O. Users must choose from a plethora of (mostly mutually incompatible) third-party libraries for GUI and other functionality. The standard library has grown with each release. By version 1.6 the library included support for locales, logging, containers and iterators, algorithms, GUI programming (but not using the system GUI), graphics, multi-threading, networking, platform security, introspection, dynamic class loading, blocking and non-blocking I/O, and provided interfaces or support classes for XML, XSLT, MIDI, database connectivity, naming services (e.g. LDAP), cryptography, security services (e.g. Kerberos), print services, and web services. SWT offers an abstraction for platform specific GUIs.
Operator overloading for most operators The meaning of operators is generally immutable, however the + and += operators have been overloaded for Strings.
Full multiple inheritance, including virtual inheritance. Single inheritance only from classes, multiple from interfaces.
Compile time Templates Generics are used to achieve an analogous effect to C++ templates, however they do not translate from source code to byte code due to the use of Type Erasure by the compiler.
Function pointers, function objects, lambdas (in C++11, formerly named C++0x) and interfaces No function pointer mechanism. Instead idioms such as Interfaces, Adapters and Listeners are extensively used.
No standard inline documentation mechanism. 3rd party software (e.g. Doxygen) exists. Javadoc standard documentation
const keyword for defining immutable variables and member functions that do not change the object. final provides a limited version of const, equivalent to type* const pointers for objects and plain const of primitive types only. No const member functions, nor any equivalent to const type* pointers.
Supports the goto statement. Supports labels with loops and statement blocks.
Source code can be written to be platform independent (can be compiled for Windows, BSD, Linux, Mac OS X, Solaris etc. without needing modification) and written to take advantage of platform specific features. Is typically compiled into native machine code. Is compiled into byte code for the JVM. Is dependent on the Java platform but the source code is typically written not to be dependent on operating system specific features.

C++ is a powerful language designed for a wide range of programming tasks. The Java language was designed to be simple and easy to learn with a powerful cross-platform library. The Java standard library is large for a standard library. However, Java does not always provide full access to the features and performance of the platform on which the software runs.

The C++ standard libraries provide containers and associative arrays,[2] as well as the Java library inside the Java Collections Framework.

Language features

Syntax

C++ Java
class Foo {          // Declares class Foo
public:
    int x;           // Member variable
 
    Foo(): x(0) {}   //  Constructor for Foo, initializes x to 0. 
                     //    The value is not mandatory.
 
    int bar(int i) { // Member function bar()
        return 3*i + x;
    }
};
class Foo {               // Defines class Foo
    public int x;         // Member variable, 
                          //initialized to 0 by default
 
    public Foo() {        // Constructor for Foo
    }
 
    public int bar(int i) {// Member method bar()
        return 3*i + x;
    }
}
Foo a; 
// declares a to be a Foo object value,
// initialized using the default constructor.
// Another constructor can be used as "Foo a(args);"
Foo a; 
// declares a to be a reference to a Foo object
a = new Foo(); 
// initializes using the default constructor
// Another constructor can be used as 
// "Foo a = new Foo(args);"
Foo b = a; 
// copies the contents of a to a new Foo object b;
// alternative syntax is "Foo b(a)"
Foo b = (Foo) a.clone(); 
// copies the values of all members
// of this instance if, and only if,
// Foo implements a public method called
// clone() which returns a new copy of the object
a.x = 5; // modifies the object a
a.x = 5; // modifies the object referenced by a
cout << b.x << endl; 
// outputs 0, because b is  
// a different object than a
System.out.println(b.x); 
// outputs 0, because b points to 
// a different object than a
Foo *c; 
// declares c to be a pointer to a 
// Foo object (initially
// undefined; could point anywhere)
Foo c; 
// declares c to be a reference to a Foo 
// object (initially null if c is a class member; 
// it is necessary to initialize c before use
// if it is a local variable)
c = new Foo; 
// binds c to reference a new Foo object
c = new Foo(); 
// binds c to reference a new Foo object
Foo *d = c; 
// binds d to reference the same object as c
Foo d = c; 
// binds d to reference the same object as c
c->x = 5; 
// modifies the object referenced by c
c.x = 5; 
// modifies the object referenced by c
a.bar(5);  // invokes Foo::bar() for a
c->bar(5); // invokes Foo::bar() for *c
a.bar(5); // invokes Foo.bar() for a
c.bar(5); // invokes Foo.bar() for c
cout << d->x << endl; 
// outputs 5, because d references the
// same object as c
System.out.println(d.x); 
// outputs 5, because 
// d references
// the same object as c
C++ Java
const Foo *a; // it is not possible to modify the object
              // pointed to by a through a
final Foo a; // it is possible to modify the object
a = new Foo();
a = new Foo(); // Only in constructor
a->x = 5; 
// ILLEGAL
a.x = 5; 
// LEGAL, the object can still be modified
Foo *const b = new Foo(); 
// a declaration of a "const" pointer
final Foo b = new Foo(); 
// a declaration of a "final" reference
b = new Foo(); 
//ILLEGAL, it is not allowed to re-bind it
b = new Foo(); 
// ILLEGAL, it is not allowed to re-bind it
b->x = 5; 
// LEGAL, the object can still be modified
b.x = 5; 
// LEGAL, the object can still be modified

Semantics

Resource management

Libraries

Runtime

Templates vs. Generics

Both C++ and Java provide facilities for generic programming, templates and generics, respectively. Although they were created to solve similar kinds of problems, and have similar syntax, they are actually quite different.

C++ Templates Java Generics
Classes and functions can be templated. Classes and methods can be genericized.
Parameters can be any type, integral value, or character literal. Parameters can only be reference types (not primitive types).
Separate copies of the class or function are likely to be generated for each type parameter when compiled. One version of the class or function is compiled, works for all type parameters.
Objects of a class with different type parameters are different types at run time. Type parameters are erased when compiled; objects of a class with different type parameters are the same type at run time.
Implementation source code of the templated class or function must be included in order to use it (declaration insufficient). Signature of the class or function from a compiled class file is sufficient to use it.
Templates can be specialized -- a separate implementation could be provided for a particular template parameter. Generics cannot be specialized.
Template parameters can have default arguments (only for template classes, not functions(This restriction has been removed in C++11)). Generic type parameters cannot have default arguments.
Does not support wildcards. Instead, return types are often available as nested typedefs. (Also, C++11 added keyword auto acting as a wildcard for any type that can be determined at compile time.) Supports wildcard as type parameter if it is only used once.
Does not directly support bounding of type parameters, but metaprogramming provides this[9] Supports bounding of type parameters with "extends" and "super" for upper and lower bounds, respectively; allows enforcement of relationships between type parameters.
Allows instantiation of class of type parameter type. Does not allow instantiation of class of type parameter type (except through reflection).
Type parameter of templated class can be used for static methods and variables. Type parameter of templated class cannot be used for static methods and variables.
Static variables are not shared between classes of different type parameters. Static variables are shared between instances of a classes of different type parameters.
Templated classes and functions do not enforce type relations for type parameters in their declaration. Use of a wrong type parameter results in the template code "not working", usually generating an error message at a place in the template code where an operation is not allowed for that type and not in the user's code. Proper use of templated classes and functions is dependent on proper documentation. Metaprogramming provides these features at the cost of additional effort. Generic classes and functions can enforce type relationships for type parameters in their declaration. Use of a wrong type parameter results in a type error at the code that uses it. Operations on parametrized types in generic code are only allowed in ways that can be guaranteed to be safe by the declaration. This results in greater type safety at the cost of flexibility.
Templates are Turing-complete (see template metaprogramming). Generics are not Turing-complete.

Miscellaneous

Performance

In addition to running a compiled Java program, computers running Java applications generally must also run the Java virtual machine (JVM), while compiled C++ programs can be run without external applications. Early versions of Java were significantly outperformed by statically compiled languages such as C++. This is because the program statements of these two closely related languages may compile to a few machine instructions with C++, while compiling into several byte codes involving several machine instructions each when interpreted by a JVM. For example:

Java/C++ statement C++ generated code (x86) Java generated byte code
vector[i]++; mov edx,[ebp+4h]

mov eax,[ebp+1Ch]
inc dword ptr [edx+eax*4]

aload_1

iload_2
dup2
iaload
iconst_1
iadd
iastore

Certain inefficiencies are inherent to the Java language itself, primarily:

In contrast, various optimizations in C++ are either too difficult or impractical to implement:

Official standard and reference of the language

Language specification

The C++ language is defined by ISO/IEC 14882, an ISO standard, which is published by the ISO/IEC JTC1/SC22/WG21 committee. The Java language is defined by the Java Language Specification,[16] a book which is published by Sun (now Oracle).

The Java language continuously evolves through a process called the Java Community Process, and the world's programming community is represented by a group of people and organizations - the Java Community members[17] - which is actively engaged into the enhancement of the language, by sending public requests - the Java Specification Requests - which must pass formal and public reviews before they get integrated into the language.
In contrast, the C++ programming community does not have this power, because the C++ language specification was statically defined by ISO.

Trademarks

"C++" is not a trademark of any company or organization and is not owned by any individual.[18] "Java" is a trademark of Sun Microsystems (now Oracle).[19]

References

  1. ^ "The Java Tutorials: Passing Information to a Method or a Constructor". Oracle. http://download.oracle.com/javase/tutorial/java/javaOO/arguments.html. Retrieved 2010-12-07. 
  2. ^ Java and C++ Library
  3. ^ a b Robert C. Martin (January 1997). "Java vs. C++: A Critical Comparison" (PDF). http://www.objectmentor.com/resources/articles/javacpp.pdf. 
  4. ^ "Reference Types and Values". The Java Language Specification, Third Edition. http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.3. Retrieved 9 December 2010. 
  5. ^ Horstmann, Cay; Cornell, Gary (2008). Core Java. I (Eighth ed.). Sun Microsystems. pp. 140–141. ISBN 978-0-13-235476-9. "Some programmers (and unfortunately even some book authors) claim that the Java programming language uses call by reference for objects. However, that is false. Because this is such a common misunderstanding, it is worth examining a counterexample in some detail... This discussion demonstrates that the Java programming language does not use call by reference for objects. Instead object references are passed by value." 
  6. ^ Deitel, Paul; Deitel, Harvey (2009). Java for Programmers. Prentice Hall. p. 223. ISBN 978-0-13-700129-3. "Unlike some other languages, Java does not allow programmers to choose pass-by-value or pass-by-reference—all arguments are passed by value. A method call can pass two types of values to a method—copies of primitive values (e.g., values of type int and double) and copies of references to objects (including references to arrays). Objects themselves cannot be passed to methods." 
  7. ^ "Java Language Specification 4.3.1: Objects". Sun Microsystems. http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.3.1. Retrieved 2010-12-09. 
  8. ^ "Java memory leaks -- Catch me if you can" by Satish Chandra Gupta, Rajeev Palanki, IBM DeveloperWorks, 16 Aug 2005
  9. ^ Boost type traits library
  10. ^ Clark, Nathan; Amir Hormati, Sami Yehia, Scott Mahlke (2007). "Liquid SIMD: Abstracting SIMD hardware using lightweight dynamic mapping". HPCA’07: 216–227. 
  11. ^ http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html
  12. ^ Demystifying the Restrict Keyword
  13. ^ Targeting IA-32 Architecture Processors for Run-time Performance Checking
  14. ^ http://www.azulsystems.com/blog/cliff/2011-04-04-fixing-the-inlining-problem
  15. ^ http://java.sun.com/performance/reference/whitepapers/6_performance.html#2.1.1
  16. ^ The Java Language Specification
  17. ^ http://www.jcp.org/en/participation/members
  18. ^ Bjarne Stroustrup's FAQ: Do you own C++?
  19. ^ ZDNet: Oracle buys Sun; Now owns Java.

External links